import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'package:ball_lion/module/home/news_list_logic.dart';
import 'package:ball_lion/entity/expert/expert_hot_entity.dart';
import 'package:ball_lion/entity/other/resource_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/items/league_hot_expert.dart';
import 'package:ball_lion/widgets/base/wqs_carousel_view.dart';
import 'package:ball_lion/module/home/news_button_area.dart';
import 'package:ball_lion/module/home/news_cell.dart';
import 'package:ball_lion/module/home/news_match_view.dart';
import 'package:ball_lion/module/home/post_cell.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/base/wqs_button.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'package:ball_lion/widgets/scroll_bar.dart';
import 'package:ball_lion/module/loading/loading_home_widget.dart';
import 'package:ball_lion/base/base_builder.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class NewsListView extends StatefulWidget {
  const NewsListView({Key? key, this.id, this.isHome = true}) : super(key: key);

  final String? id;
  final bool isHome;

  @override
  State<NewsListView> createState() => _NewsListViewState();
}

class _NewsListViewState extends State<NewsListView>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  late final NewsListLogic logic = Get.put(NewsListLogic(), tag: widget.id);
  final visibleKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return RefreshBuilder<NewsListLogic>(
      tag: widget.id,
      refreshController: logic.refreshController,
      scrollController: logic.refreshScroll,
      header: Styles.refreshHeader(position: IndicatorPosition.locator),
      footer: Styles.refreshFooter(position: IndicatorPosition.locator),
      needLoad: true,
      initState: (state) => logic.id = widget.id,
      builder:
          (NewsListLogic logic, BuildContext context, ScrollPhysics physics) {
        return VisibilityDetector(
          key: visibleKey,
          onVisibilityChanged: (info) {
            logic.visible = !info.visibleBounds.isEmpty;
            if (logic.config != null && logic.visible) {
              logic.getResources();
            }
          },
          child: LoadingWidget<bool>(
            isLoading: logic.newsItems == null,
            physics: physics,
            reconnect: logic.getRefresh,
            loading: CustomScrollView(
              physics: physics,
              controller: logic.refreshScroll,
              slivers: const [
                HeaderLocator.sliver(),
                SliverToBoxAdapter(child: LoadingHomeWidget()),
                FooterLocator.sliver()
              ],
            ),
            data: false,
            child: () => CustomScrollView(
              physics: physics,
              controller: logic.refreshScroll,
              slivers: [
                const HeaderLocator.sliver(),
                SliverToBoxAdapter(
                  child: Container(
                    decoration: const BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colours.white, Colours.greyF2F3F7],
                            begin: Alignment.topCenter,
                            end: Alignment.bottomCenter,
                            stops: [0, 0.6])),
                    child: Column(
                      children: [
                        if (logic.carousals.isNotEmpty)
                          QsCarouselView(
                            carousels: logic.carousals,
                            aspectRatio: 359 / 120,
                            radius: 8,
                            padding: 8,
                            needDot: logic.carousals.length > 1,
                            carouselController: logic.carouselController,
                            tapType: "home_${logic.id}_banner",
                          ).marginOnly(top: 8),
                        SizedBox(
                            width: Get.width,
                            child: ScrollBoard(
                                type: widget.id ?? "",
                                margin: const EdgeInsets.fromLTRB(8, 8, 8, 0))),
                        if (logic.collection.isNotEmpty)
                          collectionWidget().marginOnly(top: 12),
                        if (logic.newsMatches.isNotEmpty)
                          NewsMatchView(
                            matches: logic.newsMatches,
                            click: (p0) {
                              Utils.onEvent("home_${logic.id}_match",
                                  params: {"id": p0.id});
                              Get.toNamed(Routes.zqMatchDetail,
                                  arguments: p0.id);
                            },
                          ).marginOnly(top: 8),
                        if (logic.menus.isNotEmpty)
                          Block(
                            cardStyle: const CardStyle(
                                margin: EdgeInsets.fromLTRB(8, 8, 8, 0)),
                            child: NewsButtonArea(
                              menus: logic.menus,
                              tapType: "home_${logic.id}_portal",
                            ),
                          ),
                        if (logic.boardController != null)
                          HotExpertBoard(
                            controller: logic.boardController!,
                          ).paddingOnly(top: 8, left: 8, right: 8)
                        // const SizedBox(height: 16,),
                      ],
                    ),
                  ),
                ),
                SliverList(
                    delegate: SliverChildBuilderDelegate((context, index) {
                  if (logic.hotExpert.isNotEmpty &&
                      index == logic.topNewsCount) {
                    return hotExpertList();
                  } else {
                    if (logic.hotExpert.isNotEmpty &&
                        index > logic.topNewsCount) {
                      index -= 1;
                    }
                    final e = logic.newsItems?[index];
                    if (e?.type == 2) {
                      return PostCell(e!);
                    } else {
                      var style = PinStyle.none;
                      final hasTopNews = logic.topNewsCount > 0;
                      if (hasTopNews && 0 == index) {
                        style = PinStyle.top;
                      } else if (hasTopNews && index == logic.topNewsCount) {
                        style = PinStyle.normal;
                      } else if (!hasTopNews && 0 == index) {
                        style = PinStyle.normal;
                      }
                      return NewsItemCell(
                        e!,
                        inHome: true,
                        classId: logic.config?.infoClassId,
                        afterRoute: update,
                        id: widget.id,
                        style: style,
                      );
                    }
                  }
                },
                        childCount: logic.hotExpert.isEmpty
                            ? logic.newsItems?.length
                            : (logic.newsItems?.length ?? 0) + 1)),
                if (!logic.newsItems.hasValue)
                  SliverToBoxAdapter(
                      child:
                          const NoDataWidget(tip: "暂无资讯").sized(height: 400)),
                const FooterLocator.sliver()
              ],
            ),
          ),
        );
      },
    );
  }

  Widget collectionWidget() {
    return SizedBox(
      width: double.infinity,
      height: 30,
      child: ListView.builder(
        physics: const ClampingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        itemCount: logic.collection.length,
        itemBuilder: (context, index) {
          ResourceEntity entity = logic.collection[index];
          return GestureDetector(
            onTap: () {
              Utils.onEvent("zxhj", params: {"zxhj": "$index"});
              Get.toNamed(Routes.newsList,
                  arguments: entity.content,
                  parameters: {'title': entity.title ?? ''});
            },
            child: Container(
              width: 102,
              height: 30,
              decoration: BoxDecoration(
                  color: Colours.white,
                  border: Border.all(color: Colours.greyEE),
                  borderRadius: BorderRadius.circular(15)),
              padding: const EdgeInsets.symmetric(horizontal: 8),
              margin: EdgeInsets.only(
                  left: index == 0 ? 8 : 0,
                  right: index == logic.collection.length - 1 ? 8 : 8),
              child: Row(
                children: [
                  ClipOval(
                      child: CachedNetworkImage(
                          imageUrl: entity.imgUrl ?? '',
                          width: 16,
                          height: 16,
                          fit: BoxFit.cover)),
                  const SizedBox(width: 2),
                  Expanded(child: QsText(entity.title ?? '', maxLines: 1)),
                  Image.asset(Utils.getImgPath('arrow_right.png'),
                      width: 6, height: 10)
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget hotExpertList() {
    List<Color> colors = const [
      Color(0xFFFFEEE6),
      Color(0xFFECF7FF),
      Color(0xFFFFF5D8),
      Color(0xFFF0F1FF)
    ];
    return Block(
        cardStyle: const CardStyle(
          height: 175,
          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
        ),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Image.asset(Utils.getImgPath("expert_hot_bg.png")),
            Padding(
              padding: const EdgeInsets.only(top: 12, bottom: 16),
              child: Column(
                children: [
                  Row(
                    children: [
                      const SizedBox(width: 12),
                      Image.asset(Utils.getImgPath('reword_icon.png'),
                          width: 20),
                      const SizedBox(width: 4),
                      QsText('关注他们，及时获取赛场信息',
                          fontWeight: FontWeight.w500, fontSize: 15),
                      const Spacer(),
                      QsButton(
                          height: 20,
                          widget: Row(children: [
                            QsText(
                              '全部',
                              color: Colours.grey66,
                              fontSize: 12,
                            ),
                            const SizedBox(width: 5),
                            Image.asset(Utils.getImgPath('arrow_right.png'),
                                width: 6, height: 10)
                          ]),
                          onPressed: () {
                            Get.toNamed(Routes.expertAll);
                          })
                    ],
                  ),
                  const SizedBox(height: 10),
                  Expanded(
                    child: ListView.builder(
                      physics: const ClampingScrollPhysics(),
                      scrollDirection: Axis.horizontal,
                      itemCount: logic.hotExpert.length,
                      itemBuilder: (context, index) {
                        NewsExpertHotEntity expert = logic.hotExpert[index];
                        return GestureDetector(
                          onTap: () {
                            Get.toNamed(Routes.userPage,
                                arguments: expert.id,
                                parameters: {'type': '1'});
                          },
                          child: Container(
                            width: 100,
                            height: 120,
                            padding: const EdgeInsets.symmetric(horizontal: 8),
                            margin: EdgeInsets.only(
                                left: index == 0 ? 12 : 8,
                                right: index == logic.hotExpert.length - 1
                                    ? 12
                                    : 0),
                            decoration: BoxDecoration(
                                gradient: LinearGradient(
                                    colors: [
                                      colors[index % 4],
                                      Colours.transparent
                                    ],
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter),
                                borderRadius: BorderRadius.circular(8)),
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  const SizedBox(height: 8),
                                  Stack(
                                    children: [
                                      ClipOval(
                                        child: CachedNetworkImage(
                                            imageUrl: expert.logo ?? '',
                                            fit: BoxFit.cover,
                                            width: 52,
                                            height: 52),
                                      ),
                                      if ((expert.infoHot ?? 0) >= 1)
                                        Positioned(
                                            right: 0,
                                            bottom: 0,
                                            child: Image.asset(
                                                Utils.getImgPath('fire.png'),
                                                width: 16))
                                    ],
                                  ),
                                  const SizedBox(height: 4),
                                  QsText(expert.name ?? '',
                                      maxLines: 1, fontWeight: FontWeight.w500),
                                  const SizedBox(height: 1),
                                  QsText(expert.info ?? '',
                                      maxLines: 2,
                                      color: Colours.grey99,
                                      fontSize: 10)
                                ]),
                          ),
                        );
                      },
                    ),
                  )
                ],
              ),
            ),
          ],
        ));
  }
}
